const { join } = require('path')

/**
 *
 * @param {*} originalConfigFn param: ({packageJson, region, dir, simpleBuild}) => {}
 * @returns
 */
function wrapConfigFn(originalConfigFn) {
  return (param) =>
    ({ packageJson } = {}) =>
      originalConfigFn({
        packageJson,
        ...param,
        simpleBuild: !!process.env.SIMPLE_BUILD,
        isDevelopment: process.env.NODE_ENV === 'development',
      })
}
/**
 *
 * @param {*} configFn param: ({ packageJson,simpleBuild: !!process.env.SIMPLE_BUILD }) => {}
 * @returns
 */
function parseDirWithRollupConfig(configFn) {
  if (typeof configFn !== 'function') return
  const targetPkgDir = process.cwd()
  const packageJson = require(join(targetPkgDir, 'package.json'))
  const configs = configFn({
    packageJson,
    simpleBuild: !!process.env.SIMPLE_BUILD,
    isDevelopment: process.env.NODE_ENV === 'development',
  })
  if (!configs) return
  const parseDir = (configItem) => {
    const parserOutput = (outputConfig) => ({
      ...outputConfig,
      dir: outputConfig.dir ? join(targetPkgDir, outputConfig.dir) : null,
      file: outputConfig.file ? join(targetPkgDir, outputConfig.file) : null,
    })
    return {
      ...configItem,
      input: join(targetPkgDir, configItem.input),
      output: Array.isArray(configItem.output) ? configItem.output.map(parserOutput) : parserOutput(configItem.output),
    }
  }

  if (Array.isArray(configs)) {
    return configs.map(parseDir)
  }
  return parseDir(configs)
}

module.exports = {
  parseDirWithRollupConfig,
  wrapConfigFn,
}
